import platform

import falcon
import psutil
import os
import time
import json
from datetime import datetime, timedelta

from WebBackend.middleware.virtualWorldGate_Chuche import login_require


@falcon.before(login_require)
class SystemInfoAPI:
    async def on_get(self, req: falcon.Request, resp: falcon.Response):
        system_info = {
            "hostname": platform.node(),
            **get_linux_distribution(),
            **get_cpu_info(),
            **get_memory_info(),
            **get_system_uptime(),
        }
        resp.media = system_info


def get_linux_distribution():
    """获取 Linux 分发名称和版本号"""
    try:
        with open("/etc/os-release") as f:
            lines = f.readlines()
            dist_info = {}
            for line in lines:
                if "=" in line:
                    key, value = line.strip().split("=", 1)
                    dist_info[key] = value.strip('"')
            return {
                "distribution": dist_info.get("PRETTY_NAME", "Unknown"),
                "version_id": dist_info.get("VERSION_ID", "Unknown")
            }
    except FileNotFoundError:
        return {
            "distribution": platform.system(),
            "version_id": platform.release()
        }


def get_cpu_info():
    """获取 CPU 名称、核心数、线程数、架构"""
    cpu_name=''
    with open("/proc/cpuinfo", "r") as f:
        for line in f:
            if "model name" in line:
                cpu_name = line.split(":")[1].strip()
                break
    return {
        "cpu_name": cpu_name or platform.processor() or psutil.cpu_freq().current,
        "cpu_cores": psutil.cpu_count(logical=False),
        "cpu_threads": psutil.cpu_count(logical=True),
        "cpu_architecture": platform.machine()
    }


def get_memory_info():
    """获取内存和 SWAP 容量（单位：GB）"""
    mem = psutil.virtual_memory()
    swap = psutil.swap_memory()
    return {
        "memory_total_gb": round(mem.total / (1024 ** 3), 2),
        "swap_total_gb": round(swap.total / (1024 ** 3), 2) if swap.total > 0 else 0.0
    }


def get_system_uptime():
    """获取系统运行时长和开机时间"""
    boot_time = psutil.boot_time()
    uptime = timedelta(seconds=time.time() - boot_time)
    return {
        "os_uptime": str(uptime),
        "boot_time": datetime.fromtimestamp(boot_time).strftime("%Y-%m-%d %H:%M:%S")
    }
